package com.yangtao.springbootfreemarker.domain.sys.service.impl;

import com.yangtao.core.exception.ServiceException;
import com.yangtao.core.jpa.service.impl.BaseJpaServiceImpl;
import com.yangtao.core.shiro.ShiroConstants;
import com.yangtao.core.shiro.util.ShiroUtils;
import com.yangtao.core.utils.RandomUtil;
import com.yangtao.core.utils.StringUtil;
import com.yangtao.springbootfreemarker.domain.sys.dao.SysUserDao;
import com.yangtao.springbootfreemarker.domain.sys.entity.SysUser;
import com.yangtao.springbootfreemarker.domain.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysUserServiceImpl extends BaseJpaServiceImpl<SysUser, String, SysUserDao> implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    protected void beforeSave(SysUser sysUser) {
        if(StringUtil.isEmpty(sysUser.getPassword())) {
            throw new ServiceException("密码不能为空");
        }
        if(!StringUtil.equals(sysUser.getPassword(), SysUser.SHOW_PASSWORD)) { // 验证是否已经修改了密码
            // 生成盐
            String salt = RandomUtil.randomString(20);
            // 设置盐
            sysUser.setSalt(salt);
            // 生成密码
            sysUser.setPassword(ShiroUtils.shaMd5(sysUser.getUsername(), sysUser.getPassword(), sysUser.getSalt()));
        }
    }

    @Override
    public SysUser getSysUserInfoByName(String username) {
        return sysUserDao.findOne("username", username);
    }

    @Override
    public List<String> queryAllPerms(String userId) {
        return sysUserDao.queryAllPerms(userId);
    }
}
